const path = require('path');
const fs= require("fs")
const webpack = require('webpack');
const tsImportPluginFactory = require('ts-import-plugin');
const { env: { activity = 'demo', NODE_ENV='development', APP_ENV="development" } } = process;

const activityConfig = require(`./src/activities/${activity}/config.js`);

const { devServer, page = {}, thirdUnable = {}, baseUrl = {} } = activityConfig;
const reqUrl = baseUrl[APP_ENV] || '/';
const { cdnActivitys } = require('./cdn.config');
const mixin = path.resolve(`./src/activities/${activity}/mixin.scss`);
const additionalData = fs.existsSync(mixin) ? `@import "~@/lib/css/mixin.scss"; @import "~@/activities/${activity}/mixin.scss";` : `@import "~@/lib/css/mixin.scss";`;
/**
 * @description 根据环境以及活动判断是否用外部CDN,及外部CDN链接
 */
const getPublicPath = () => {
  if(cdnActivitys[activity]){
    if(['production'].includes(APP_ENV)){
      return `https://static.heiheiyuyin.com/h5-activity/dist/${activity}`
    }
    return '.'
  }
  return '.';
}

/**
 * @description 生成outpath
 */
const getOutPath = () => {
  if(APP_ENV === 'test'){
    return  `dist/${APP_ENV}/${activity}`;
  }else{
    return `dist/${activity}`
  }
}


module.exports = {
  devServer,
  pages: {
    [activity]: page
  },
  chainWebpack: (config) => {
    config.plugin('define').use(webpack.DefinePlugin, [{
      'process.env': {
        activity: `"${activity}"`,
        NODE_ENV: `"${NODE_ENV}"`,
        APP_ENV: `"${APP_ENV}"`,
        baseUrl: `"${reqUrl}"`,
        PUBLIC_PATH: `"${getPublicPath()}"`,
        thirdUnable,
      }
    }])

    config.plugin('copy').tap(args => {
      args[0].push({
        ...args[0][0],
        from: path.resolve(__dirname, `./src/activities/${activity}/static`),
        to: `${args[0][0].to}/static`
      });
      return args;
    })

    config.module
      .rule('svg')
      .exclude.add(path.resolve(__dirname, './src/lib/icons'))
      .end();
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(path.resolve(__dirname, './src/lib/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end();

    config.module
      .rule('jsx')
      .test(/\.(jsx|tsx)$/)
      .include.add(path.resolve(__dirname, './src'))
      .end()
      .use('@ant-design-vue/vue-jsx-hot-loader')
      .loader('@ant-design-vue/vue-jsx-hot-loader')
      .end();
  },
  pluginOptions: {
    htmlWebpack: {
      keywords: page.keywords,
      description: page.description,
      content: page.content
    }
  },
  configureWebpack: config => {
    config.module = {
      rules: [
        ...config.module.rules,
        {
          test: /\.(jsx|tsx|js|ts)$/,
          loader: 'ts-loader',
          options: {
            happyPackMode: true,
            transpileOnly: true,
            getCustomTransformers: () => ({
              before: [ tsImportPluginFactory({
                libraryName: 'vant',
                libraryDirectory: 'es',
                style: true
              }) ]
            }),
            compilerOptions: {
              module: 'es2015'
            }
          },
          exclude: /node_modules/
        }
      ]
    }
  },
  outputDir: getOutPath(),
  publicPath: getPublicPath(),
  productionSourceMap: false,
  css: {
    loaderOptions: {
      css: {
        localsConvention: 'camelCaseOnly'
      },
      scss: {
        additionalData
      }
    }
  },
  lintOnSave: false,
  parallel: false
}
